package com.etc.SendAndRecive;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class FileTransfer {
    private static InputStream is = null;
    private static OutputStream os = null;
    private static FileInputStream fis = null;
    private static FileOutputStream fos = null;
    private static byte[] buf = new byte[1024];

    public static boolean Send(Socket socket, String FilePath) {
        try {
            os = socket.getOutputStream();
            fis = new FileInputStream(FilePath);

            while (fis.read(buf) > 0) {
                os.write(buf);
            }

            return true;
        } catch (Exception e) {
            e.printStackTrace();

            return false;
        } finally {
            closeAll();
        }
    }

    public static boolean Receive(Socket socket, String FilePath) {
        try {
            is = socket.getInputStream();
            fos = new FileOutputStream(FilePath);

            while (is.read(buf) > 0) {
                fos.write(buf);
            }

            return true;
        } catch (Exception e) {
            e.printStackTrace();

            return false;
        } finally {
            closeAll();
        }
    }

    public static void closeAll() {
        try {
            if (is != null) {
                is.close();
            }
            if (os != null) {
                os.close();
            }
            if (fis != null) {
                fis.close();
            }
            if (fos != null) {
                fos.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
